package com.zdj;

/**
 * @author zhangdj
 * @date 2021-10-21 10:45:59
 * 找到两个字符串中的最大子串
 */
public class MaxSubString {

    public static void main(String[] args) {
        System.out.println(getMaxSubString("brtubfryjb", "ubfr"));
    }

    public static String getMaxSubString(String s1, String s2) {
        if (s1 == null || s2 == null) {
            return null;
        }
        int n1 = s1.length();
        int n2 = s2.length();
        if (n1 <= 0 || n2 <= 0) {
            return "";
        }
        // 记录最长子串
        StringBuilder result = new StringBuilder();
        char[] arr1 = s1.toCharArray();
        char[] arr2 = s2.toCharArray();
        // abc   iuab
        // 遍历字符串 如果另一个字符串中存在该字符，记录结果，并进行下一次比较；
        for (int i = 0; i < n1; i++) {
            char c = arr1[i];
            if (s2.contains(c + "")) {
                StringBuilder temp = new StringBuilder();
                // 找到字符索引
                int k = s2.indexOf(c);
                temp.append(c);
                int index = i;
                index++;
                for (int j = k + 1; j < n2; j++) {
                    // 如果后续字符串依旧相同 记录字符串
                    if (i < n1 - 1 && arr1[index++] == arr2[j]) {
                        temp.append(arr2[j]);
                    } else {
                        break;
                    }
                }
                if (temp.length() > result.length()) {
                    result = temp;
                }
            }
        }
        return result.toString();
    }
}
